import time,datetime,json
from tkinter import N
from uuid import uuid4
from django.shortcuts import redirect
from django.forms.models import model_to_dict
from website_server.settings import SITE_Domain_Name
from django.http.response import HttpResponse
# 生成当前时间格式
def getTime():
  return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 

# 生成唯一id
def getID():
  uuidChars = ("a", "b", "c", "d", "e", "f","g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
             "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
             "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
             "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
             "W", "X", "Y", "Z")
  uuid = str(uuid4()).replace('-', '')
  result = ''
  for i in range(8):
    sub = uuid[i * 4: i * 4 + 4]
    x = int(sub,16)
    result += uuidChars[x % 0x3E]
  return result

# 时间序列化
class CJsonEncoder(json.JSONEncoder):
  def default(self, obj):
    if isinstance(obj, datetime.datetime):
      # 这里可以统一修改想要的格式
      return obj.strftime('%Y-%m-%d %H:%M:%S')
    elif isinstance(obj, datetime.date):
      # 这里可以统一修改想要的格式
      return obj.strftime('%Y-%m-%d')
    else:
      return json.JSONEncoder.default(self, obj)

# 模型数据集转列表
def model_to_list(Q):
  result = [model_to_dict(i) for i in Q]
  return result

# 登陆权限验证
def log_in(func):
  def wrapper(request):
    if request.method == 'POST' and (request.session.get('user') != None or request.session.get('admin') != None):
      return func(request)
    elif request.session.get('user') == None:
      return HttpResponse('登陆已过期,请重新登录')
    else:
      return redirect(SITE_Domain_Name)
  return wrapper

# 管理员登陆权限验证
def log_in_admin(func):
  def wrapper(request):
    if request.method == 'POST' and request.session.get('admin') != None:
      return func(request)
    elif request.session.get('admin') == None:
      return HttpResponse('登陆过期!')
    else:
      return redirect(SITE_Domain_Name + 'Admin')
  return wrapper

# 防盗链
def http_post(func):
  def wrapper(request):
    if request.method == 'POST':
      return func(request)
    else:
      return redirect(SITE_Domain_Name)
  return wrapper
